<?php

namespace app\models;

use Yii;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;

/**
 * This is the model class for table "zs_role_task".
 *
 * @property integer $id
 * @property integer $role_id
 * @property integer $task_id
 * @property integer $create_time
 */
class RoleTask extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'zs_role_task';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['role_id' , 'task_id' ], 'required'],
            [['id', 'role_id', 'task_id', 'create_time'], 'integer']
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'role_id' => '角色id',
            'task_id' => '任务id',
            'create_time' => '创建时间',
        ];
    }

    public function behaviors()
    {
        return [
            [
                'class' => TimestampBehavior::className(),
                'attributes' => [
                    ActiveRecord::EVENT_BEFORE_INSERT => ['create_time'],
                ],
            ],


        ];
    }

    public function getTask()
    {
        return $this->hasOne(Task::className(),['task_id' => 'task_id']);
    }

    public function getRoleTaskByBothId()
    {
        if(!$this->task_id || !$this->role_id ){
            return false;
        }

        return $this->findOne(['task_id' => $this->task_id,'role_id' => $this->role_id]);
    }

    public function getAllTasksByRoleId()
    {
        if(!$this->role_id ){
            return false;
        }

        $tasks = $this->find()->where(['role_id' => $this->role_id])->select(['task_id'])->with('task')->asArray()->all();
        if(empty($tasks)){
            return [];
        }
        $result = [];
        foreach($tasks as $task){
            $result[$task['task_id']] = $task['task']['task_name'];
        }

        return $result;
    }
}
